package com.itya.weatherback.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itya.weatherback.domain.getWeatherAli.vo.User;
import com.itya.weatherback.mapper.UserMapper;
import com.itya.weatherback.service.UserService;
import com.itya.weatherback.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@RestController
@RequestMapping("/book")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/login")
    public Result<User> login(@RequestParam(value = "username", required = false) String username,
                              @RequestParam(value = "password", required = false) String password) {
        try {
            // 对输入的密码进行加密
            String encryptedPassword = encryptPassword(password);

            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getUsername, username);
            wrapper.eq(User::getPassword, encryptedPassword); // 使用加密后的密码查询

            User user = userMapper.selectOne(wrapper);
            if (user != null) {
                user.setPassword(null); // 不返回密码信息
                return Result.success(user);
            } else {
                return Result.error("用户名或密码错误");
            }
        } catch (Exception e) {
            return Result.error("登录失败");
        }
    }

    @PostMapping("/register")
    public Result<User> register(@RequestBody User user) {
        try {
            // 检查用户名是否已存在
            LambdaQueryWrapper<User> checkWrapper = new LambdaQueryWrapper<>();
            checkWrapper.eq(User::getUsername, user.getUsername());
            if (userMapper.selectCount(checkWrapper) > 0) {
                return Result.error("用户名已存在");
            }

            // 注册新用户，对密码进行加密
            User userRegister = new User();
            userRegister.setUsername(user.getUsername());
            // 对密码进行简单加密
            userRegister.setPassword(encryptPassword(user.getPassword()));

            userMapper.insert(userRegister);
            userRegister.setPassword(null); // 不返回密码数据
            return Result.success(userRegister);
        } catch (Exception e) {
            return Result.error("注册失败");
        }
    }

    /**
     * 简单密码加密方法 - 使用MD5
     * @param password 原始密码
     * @return 加密后的密码
     */
    private String encryptPassword(String password) {
        if (password == null) return null;

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(password.getBytes());
            byte[] digest = md.digest();

            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b & 0xff));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            // 如果MD5不可用，则使用简单替代方案
            return password + "_encrypted";
        }
    }
}
